package fire.and.near.challenger;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Response;

import fire.and.near.challenger.camera.CameraHelper;
import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.FriendModel;
import fire.and.near.challenger.database.TableConstants.ChallengesTable;
import fire.and.near.challenger.database.TableConstants.FriendsTable;
import fire.and.near.challenger.dialogs.ChallengeDialogFragment;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.FacebookHelper;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.Consts;
import fire.and.near.challenger.web.HttpRequestSender;

public class ChallengeDetailsActivity extends ActionBarActivity implements
		DatabaseActivity {

	private ChallengeModel mModel = new ChallengeModel();
	private FacebookHelper mFbHelper = LoginActivity.mFbHelper;
	private boolean isShared = false;
	private boolean isDeleted = false;
	protected int finalHeight;
	protected int finalWidth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_challenge_details);

		if (savedInstanceState == null) {
			Bundle extras = getIntent().getExtras();
			initChallengeView(extras);
		}
	}

	private void initChallengeView(Bundle extras) {

		initChallengeModel(extras);

		if (mModel.getDescription() != null) {
			((TextView) findViewById(R.id.textView_description)).setText(mModel
					.getDescription());
		} else {
			findViewById(R.id.textView_description).setVisibility(View.GONE);
		}

		if (mModel.getAnswer() != null) {
			((TextView) findViewById(R.id.textView_answer)).setText(mModel
					.getAnswer());
		} else {
			findViewById(R.id.textView_answer).setVisibility(View.GONE);
		}

		if (mModel.getChallenger().getName() != null) {
			((TextView) findViewById(R.id.textView_friend_name)).setText(mModel
					.getChallenger().getName());
		} else if(mModel.getChallengedID() == mModel.getChallenger().getFbID()) {
			((TextView) findViewById(R.id.textView_friend_name)).setText(Consts.ME);
		} else {
			((TextView) findViewById(R.id.textView_friend_name)).setText(Consts.COMPANY_NAME);
		}

		if (mModel.getPhotoPath() != null) {
			final ImageView ivPreview = (ImageView) findViewById(R.id.imageView_photo);

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			
			BitmapFactory.decodeFile(mModel.getPhotoPath(), options);
			
			int width = ivPreview.getWidth();
			int height = ivPreview.getHeight();
			
			options = CameraHelper
					.makeSampleOptions(this, options, width, height);
			
			options.inJustDecodeBounds = false;

			final Bitmap bitmap = BitmapFactory.decodeFile(mModel.getPhotoPath(),
					options);

			ivPreview.setImageBitmap(bitmap);
		} else {
			// TODO: better ideas?
			((ImageView) findViewById(R.id.imageView_photo))
					.setImageDrawable(getResources().getDrawable(
							R.drawable.camera_placeholder));
		}

		if (!mModel.isAccepted()) {
			((Button) findViewById(R.id.button_share_fb))
					.setVisibility(View.GONE);
			LayoutParams params = new android.widget.LinearLayout.LayoutParams(
					android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 2f);
			((Button) findViewById(R.id.button_delete_challenge))
					.setLayoutParams(params);
		}
	}

	private void initChallengeModel(Bundle extras) {
		mModel.setID(extras.getInt(ChallengesTable.ID));
		mModel.setDescription(extras.getString(ChallengesTable.DESCRIPTION));
		mModel.setAnswer(extras.getString(ChallengesTable.ANSWER));
		mModel.setHashtag(extras.getString(ChallengesTable.HASHTAG));
		mModel.setPhotoPath(extras.getString(ChallengesTable.PHOTO_PATH));
		mModel.setChallengedID(extras.getLong(ChallengesTable.CHALLENGED_ID));
		FriendModel challenger = new FriendModel();
		challenger.setFbID(extras.getLong(ChallengesTable.CHALLENGER_ID));
		challenger.setName(extras.getString(FriendsTable.NAME));
		mModel.setChallenger(challenger);
		mModel.setAccepted(extras.getBoolean(ChallengesTable.ACCEPTED));
	}

	public void shareOnFacebook(View v) {

		final Button btn = (Button) v;
		final Context context = this;

		if (!isShared) {
			if (!HttpRequestSender.isNetworkAvailable(this)) {
				HttpRequestSender.connectingToServerErrorMessage(this);
				return;
			}

			btn.setEnabled(false);
			
			findViewById(R.id.progressBarDetails).setVisibility(View.VISIBLE);

			Bitmap bitmap = null;

			if (mModel.getPhotoPath() != null) {
				bitmap = BitmapFactory.decodeFile(mModel.getPhotoPath());
			}

			MessageBuilder msgBuilder = new MessageBuilder(
					mModel.getDescription(), mModel.getAnswer(),
					mModel.getHashtag(), MessageType.CompleteChallenge);

			mFbHelper.postStatusUpdate(this, msgBuilder.build(), ""
					+ mModel.getChallenger().getFbID(), bitmap,
					new FacebookActionAdapter() {
						@Override
						public void onActionCompleted(Response response) {
							if (response.getError() == null) {
								Log.i("SHARE", "Success");
								Toast.makeText(context, "Shared on Facebook!", Toast.LENGTH_SHORT).show();
								btn.setText(Consts.CLOSE);
								isShared = true;
							}

							findViewById(R.id.progressBarDetails)
								.setVisibility(View.GONE);
							
							btn.setEnabled(true);
						}
					});
		} else {
			finish();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (HttpRequestSender.isNetworkAvailable(this)) {
			mFbHelper.onActivityResult(this, requestCode, resultCode, data);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			if (HttpRequestSender.isNetworkAvailable(this)) {
				LoginActivity.mFbHelper.logout();
			}

			finish();
			return true;
		}

		if (id == R.id.action_details) {
			Intent i = new Intent(this, UserDetailsActivity.class);
			startActivity(i);

			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	public void deleteChallenge(View view) {
		if (isDeleted) {
			return;
		}
		isDeleted = true;

		Bundle b = new Bundle();
		b.putInt(ChallengesTable.ID, this.mModel.getID());
		b.putString(Consts.QUESTION,
				getResources().getString(R.string.question_delete));
		b.putInt(Consts.OPTION, 2);

		ChallengeDialogFragment dialog = new ChallengeDialogFragment();
		dialog.setArguments(b);
		dialog.show(getSupportFragmentManager(),
				ChallengeDialogFragment.class.getName());
	}

	@Override
	public void processDatabaseResponse(DatabaseResponse result) {
		if (result.isSuccessful()) {
			Toast.makeText(this, "Challenge deleted", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "Could not delete challenge",
					Toast.LENGTH_LONG).show();
		}

		finish();
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		this.isDeleted = working;

	}
}
